package com.twang.stock.service.jinyan;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.twang.stock.entity.*;
import com.twang.stock.mapper.*;
import com.twang.stock.common.CommonUtils;
import com.twang.stock.enmu.HotTagEnum;
import com.twang.stock.enmu.UserBusinessTypeEnum;
import com.twang.stock.service.UserService;
import com.twang.stock.task.old.QinXuGaoDuTask;
import com.twang.stock.task.old.UpdateToDayVol;
import com.twang.stock.utils.date.HolidayCopy;
import lombok.extern.slf4j.Slf4j;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class QinXUZhiShuService {


    @Resource
    private HotTagMapper hotTagMapper;

    @Resource
    private StockTagMapper stockTagMapper;

    @Resource
    private CompanyCodeInfoMapper companyCodeInfoMapper;

    @Autowired
    private UpdateToDayVol updateToDayVol;
    @Resource
    private QinXuZhiShuMapper qinXuZhiShuMapper;
    @Autowired
    private HolidayService holidayService;

    @Autowired
    @Lazy
    private StockInfoService stockInfoService;

    @Resource
    private DuanXianBaoMapper duanXianBaoMapper;

    @Resource
    private GaiNianZiJingPaiHangMapper gaiNianZiJingPaiHangMapper;

    @Resource
    private UserService userService;

    @Resource
    private UserBusinessTypeService userBusinessTypeService;

    @Autowired
    private QinXuGaoDuTask qinXuGaoDuTask;

    @Resource
    private UserBusinessTypeMapper userBusinessTypeMapper;

    private static HotTagEnum[] enums = {HotTagEnum.Core_3, HotTagEnum.Core_2, HotTagEnum.Core_4, HotTagEnum.Core_1, HotTagEnum.Core_6};

    private static HotTagEnum[] enumByDay = {HotTagEnum.CORE_DUAN_XIAN_BAO};

    public List<QinXuZhiShu> queryList() {
        return qinXuZhiShuMapper.selectAll();
    }

    public List<HotTag> queryListByTag(HotTagEnum hotTagEnum) {
        User user=userService.getUserByToken();
        Example example = new Example(HotTag.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andLike("hotTag", hotTagEnum.getCode() + "%");
        criteria.andEqualTo("userId",user.getId());
        example.orderBy("hotTemperatureName").asc();
        List<HotTag> list = hotTagMapper.selectByExample(example);
        BigDecimal amount = BigDecimal.ZERO;
        if (!CollectionUtils.isEmpty(list)) {
            for (HotTag item : list) {
                amount = amount.add(new BigDecimal(item.getHotTemperature()));
                item.setHotTemperature(amount.floatValue());
            }
        }
        return list;
    }

    /**
     * 短线宝推荐
     *
     * @return
     */
    public List<DuanXianBao> queryDuanXianBao() {
        return duanXianBaoMapper.selectAll();
    }

    /**
     * 短线宝-推荐-大于市值
     *
     * @return
     */
    public List<QinXuZhiShu> duanxian() {
        getByTagKeyByDay(HotTagEnum.CORE_DUAN_XIAN_BAO);
        List<QinXuZhiShu> result = Lists.newArrayList();
        for (HotTagEnum hotTagEnum : enumByDay) {
            List<QinXuZhiShu> qinXuZhiShuList = qinXuZhiShuMapper.queryList(hotTagEnum.getMessage() + "_" + holidayService.getDayByNum(0));
            qinXuZhiShuList.forEach(item -> {
                result.add(item);
            });
        }
        return result;
    }

    /**
     * 短线宝-推荐-大于市值-上个交易
     *
     * @return
     */
    public List<QinXuZhiShu> duanxianYesterDay() {
        // getByTagKeyByDay(HotTagEnum.CORE_DUAN_XIAN_BAO);
        List<QinXuZhiShu> result = Lists.newArrayList();
        for (HotTagEnum hotTagEnum : enumByDay) {
            List<QinXuZhiShu> qinXuZhiShuList = qinXuZhiShuMapper.queryList(hotTagEnum.getMessage() + "_" + holidayService.getDayByNum(1));
            qinXuZhiShuList.forEach(item -> {
                result.add(item);
            });
        }
        return result;
    }


    public List<GaiNianZiJingPaiHang> queryGaiNianPaiHang(GaiNianZiJingPaiHang request) {
        Example example = new Example(GaiNianZiJingPaiHang.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotEmpty(request.getType())) {
            criteria.andEqualTo("type", request.getType());
        }
        if (StringUtils.isNotEmpty(request.getDate())) {
            criteria.andEqualTo("date", request.getDate());
        }
        if (StringUtils.isNotEmpty(request.getHanYe())) {
            criteria.andEqualTo("hanYe", request.getHanYe());
        }
        example.orderBy("date").desc();
        return gaiNianZiJingPaiHangMapper.selectByExample(example);
    }

    public List<StockInfo> queryCoreList() {
        List<StockInfo> stockInfoList = Lists.newArrayList();
        for (HotTagEnum hotTagEnum : enums) {
            //查询标签
            HotTag param = new HotTag();
            String tag = hotTagEnum.getCode();
            param.setHotTag(tag);
            HotTag record = hotTagMapper.selectOne(param);
            //查询标签关联的权重个个股
            StockTag stockTag = new StockTag();
            stockTag.setTagId(record.getId());
            List<StockTag> stockTagList = stockTagMapper.select(stockTag);
            stockTagList.forEach(item -> {
                CompanyCodeInfo companyCodeInfo = companyCodeInfoMapper.selectByPrimaryKey(item.getStockId());
                StockInfo stockInfo;
                if (holidayService.isWorkDay(HolidayCopy.getRealToday()) && holidayService.isWorkDayTradeTime()) {
                    stockInfo = updateToDayVol.querySina(companyCodeInfo);
                } else {
                    stockInfo = stockInfoService.getCodeToday(companyCodeInfo.getCompanyCode(), holidayService.getDayByNum(0));
                }
                // stockInfo=stockInfoService.getCode(companyCodeInfo.getCompanyCode(),"202105010");
                if (null != stockInfo) {
                    stockInfoList.add(stockInfo);
                }
            });
        }
        return stockInfoList;
    }


    public List<DuanXianBao> queryDuanXianBaoList() {
        return duanXianBaoMapper.selectAll();
    }

    public List<QinXuZhiShu> getZhiShu() {
        query();
        List<QinXuZhiShu> result = Lists.newArrayList();
        for (HotTagEnum hotTagEnum : enums) {
            List<QinXuZhiShu> qinXuZhiShuList = qinXuZhiShuMapper.queryList(hotTagEnum.getMessage());
            qinXuZhiShuList.forEach(item -> {
                result.add(item);
            });
        }
        for (HotTagEnum hotTagEnum : enumByDay) {
            List<QinXuZhiShu> qinXuZhiShuList = qinXuZhiShuMapper.queryList(hotTagEnum.getMessage() + "_" + holidayService.getDayByNum(0));
            qinXuZhiShuList.forEach(item -> {
                result.add(item);
            });
            List<QinXuZhiShu> qinXuZhiShuListYestoDay = qinXuZhiShuMapper.queryList(hotTagEnum.getMessage() + "_" + holidayService.getDayByNum(1));
            qinXuZhiShuListYestoDay.forEach(item -> {
                result.add(item);
            });
        }
        return result;
    }


    /**
     * 生产各个板块指数情绪
     */
    public void query() {
        for (HotTagEnum hotTagEnum : enums) {
            getByTagKey(hotTagEnum);
        }
        //单独计算日期版本
        for (HotTagEnum hotTagEnum : enumByDay) {
            getByTagKeyByDay(hotTagEnum);
        }
    }

    /**
     * 算法：选择最单纯的计算
     *
     * @param hotTag
     */
    @Transactional(rollbackFor = Exception.class)
    public void getByTagKeyByDay(HotTagEnum hotTag) {
        User user = userService.getUserByToken();
        UserBusinessType userBusinessType = userBusinessTypeService.getUserBusinessType(user.getId(), UserBusinessTypeEnum.TYPE_HOT_TAG.getCode());
        if (null == userBusinessType) {
            userBusinessType = new UserBusinessType();
            Long id = qinXuGaoDuTask.initChangXianChi();
            userBusinessType.setBusinessId(id);
        }
        HotTag record = hotTagMapper.selectByPrimaryKey(userBusinessType.getBusinessId());
        //查询标签关联的权重个个股
//        StockTag stockTag = new StockTag();
//        stockTag.setTagId(record.getId());
//        List<StockTag> stockTagList = stockTagMapper.select(stockTag);
        UserBusinessType param=new UserBusinessType();
        param.setType(UserBusinessTypeEnum.TYPE_STOCK_INFO.getCode());
        param.setUserId(user.getId());
        List<UserBusinessType> userBusinessTypeList = userBusinessTypeMapper.select(param);
        List<StockInfo> stockInfoList = Lists.newArrayList();
        List<BigDecimal> bigDecimalList = Lists.newArrayList();
        userBusinessTypeList.forEach(item -> {
            CompanyCodeInfo companyCodeInfo = companyCodeInfoMapper.selectByPrimaryKey(item.getBusinessId().intValue());
            StockInfo stockInfo;
            if (holidayService.isWorkDay(HolidayCopy.getRealToday()) && holidayService.isWorkDayTradeTime()) {
                stockInfo = updateToDayVol.querySina(companyCodeInfo);
            } else {
                stockInfo = stockInfoService.getStockInfoByDateDESC(companyCodeInfo.getCompanyCode());
            }
            if (null != stockInfo) {
                bigDecimalList.add(stockInfo.getZhangdie());
                stockInfoList.add(stockInfo);
            }
        });
        BigDecimal aomunt = BigDecimal.ZERO;
        for (int i = 0; i < bigDecimalList.size(); i++) {
            aomunt = aomunt.add(null==bigDecimalList.get(i)?BigDecimal.ZERO:bigDecimalList.get(i));
        }
        if (bigDecimalList.size() > 0) {
            record.setHotTemperature((aomunt.divide(new BigDecimal(bigDecimalList.size()), 4, BigDecimal.ROUND_HALF_UP)).floatValue());
        }
        record.setUpdateTime(new Date());
        hotTagMapper.updateByPrimaryKey(record);
        if (!CollectionUtils.isEmpty(stockInfoList)) {
            QinXuZhiShu qinXuZhiShuDto = new QinXuZhiShu();
            int num = stockInfoList.stream().filter(item -> item.getNotNullZhangDie().compareTo(BigDecimal.ZERO) == 1).collect(Collectors.toList()).size();
            qinXuZhiShuDto.setZhiShu((new BigDecimal(num).divide(new BigDecimal(stockInfoList.size()), 5, BigDecimal.ROUND_HALF_UP))
                    .multiply(new BigDecimal(100)));
            qinXuZhiShuDto.setDate(stockInfoList.get(0).getDate());
            qinXuZhiShuDto.setQingxuName(jiShuanZhiShuPingJia(qinXuZhiShuDto.getZhiShu()));
            qinXuZhiShuDto.setName(hotTag.getMessage() + "_" + holidayService.getDayByNum(0));
            QinXuZhiShu qinXuZhiShu = new QinXuZhiShu();
            qinXuZhiShu.setDate(qinXuZhiShuDto.getDate());
            qinXuZhiShu.setName(qinXuZhiShuDto.getName());
            QinXuZhiShu records = qinXuZhiShuMapper.selectOne(qinXuZhiShu);
            if (null != records) {
                qinXuZhiShuDto.setCreateTime(records.getCreateTime());
                qinXuZhiShuDto.setId(records.getId());
                qinXuZhiShuDto.setModifyTime(new Date());
                qinXuZhiShuMapper.updateByPrimaryKey(qinXuZhiShuDto);
            } else {
                qinXuZhiShuDto.setCreateTime(new Date());
                qinXuZhiShuDto.setModifyTime(new Date());
                qinXuZhiShuMapper.insert(qinXuZhiShuDto);
            }
        }
        //
    }

    /**
     * 算法：选择最单纯的计算
     *
     * @param hotTag
     */
    private void getByTagKey(HotTagEnum hotTag) {
        //查询标签
        HotTag param = new HotTag();
        String tag = hotTag.getCode();
        param.setHotTag(tag);
        HotTag record = hotTagMapper.selectOne(param);
        //查询标签关联的权重个个股
        StockTag stockTag = new StockTag();
        stockTag.setTagId(record.getId());
        List<StockTag> stockTagList = stockTagMapper.select(stockTag);
        List<StockInfo> stockInfoList = Lists.newArrayList();
        stockTagList.forEach(item -> {
            CompanyCodeInfo companyCodeInfo = companyCodeInfoMapper.selectByPrimaryKey(item.getStockId());
            StockInfo stockInfo;
            if (holidayService.isWorkDay(HolidayCopy.getRealToday()) && holidayService.isWorkDayTradeTime()) {
                stockInfo = updateToDayVol.querySina(companyCodeInfo);
            } else {
                stockInfo = stockInfoService.getCodeToday(companyCodeInfo.getCompanyCode(), holidayService.getDayByNum(0));
            }
            // stockInfo=stockInfoService.getCode(companyCodeInfo.getCompanyCode(),"202105010");
            if (null != stockInfo) {
                stockInfoList.add(stockInfo);
            }
        });
        if (!CollectionUtils.isEmpty(stockInfoList)) {
            QinXuZhiShu qinXuZhiShuDto = new QinXuZhiShu();
            int num = stockInfoList.stream().filter(item -> item.getZhangdie().compareTo(BigDecimal.ZERO) == 1).collect(Collectors.toList()).size();
            qinXuZhiShuDto.setZhiShu((new BigDecimal(num).divide(new BigDecimal(stockInfoList.size()), 5, BigDecimal.ROUND_HALF_UP))
                    .multiply(new BigDecimal(100)));
            qinXuZhiShuDto.setDate(stockInfoList.get(0).getDate());
            qinXuZhiShuDto.setQingxuName(jiShuanZhiShuPingJia(qinXuZhiShuDto.getZhiShu()));
            qinXuZhiShuDto.setName(hotTag.getMessage());
            QinXuZhiShu qinXuZhiShu = new QinXuZhiShu();
            qinXuZhiShu.setDate(qinXuZhiShuDto.getDate());
            qinXuZhiShu.setName(qinXuZhiShuDto.getName());
            QinXuZhiShu records = qinXuZhiShuMapper.selectOne(qinXuZhiShu);
            if (null != records) {
                qinXuZhiShuDto.setCreateTime(records.getCreateTime());
                qinXuZhiShuDto.setId(records.getId());
                qinXuZhiShuDto.setModifyTime(new Date());
                qinXuZhiShuMapper.updateByPrimaryKey(qinXuZhiShuDto);
            } else {
                qinXuZhiShuDto.setCreateTime(new Date());
                qinXuZhiShuDto.setModifyTime(new Date());
                qinXuZhiShuMapper.insert(qinXuZhiShuDto);
            }
        }
        //
    }

    /**
     * 翻译指数
     *
     * @param zhiShu
     * @return
     */
    public String jiShuanZhiShuPingJia(BigDecimal zhiShu) {
        if (zhiShu.compareTo(new BigDecimal(15)) < 0) {
            return CommonUtils.DUAN_XIAN_BAO_QIN_XU_ZHI_SHU_LEVEL_5;
        }
        if (zhiShu.compareTo(new BigDecimal(35)) < 0) {
            return CommonUtils.DUAN_XIAN_BAO_QIN_XU_ZHI_SHU_LEVEL_4;
        }
        if (zhiShu.compareTo(new BigDecimal(65)) < 0) {
            return CommonUtils.DUAN_XIAN_BAO_QIN_XU_ZHI_SHU_LEVEL_3;
        }
        if (zhiShu.compareTo(new BigDecimal(85)) < 0) {
            return CommonUtils.DUAN_XIAN_BAO_QIN_XU_ZHI_SHU_LEVEL_2;
        }
        return CommonUtils.DUAN_XIAN_BAO_QIN_XU_ZHI_SHU_LEVEL_1;
    }
}
